﻿using LibraryManagement.Custom_Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LibraryManagement.Profile_Management.Setup
{
    public partial class MasterLocation : libMasterForm
    {
        private LibManagementEntities context;
        private enum UpdateType { New = 0, Edit = 1 }
        UpdateType eUpdateType;
        private LibraryManagement.Location OLocation;
        public MasterLocation()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                context = new LibManagementEntities();
                if (eUpdateType == UpdateType.New)
                {
                    OLocation = new Location();
                    OLocation.LocationName = txtName.Text;
                    context.Locations.Add(OLocation);
                }
                else if (eUpdateType == UpdateType.Edit)
                {
                    OLocation = context.Locations.Single(x => x.LocationId == (decimal)lsbMaster.SelectedValue);
                    OLocation.LocationName = txtName.Text;
                }
                context.SaveChanges();
                MasterLocation_Load(sender, e);
                libMasterForm_Load(sender, e);
                base.btnClear_Click(sender, e);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            eUpdateType = UpdateType.New;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            eUpdateType = UpdateType.Edit;
        }

        private void MasterLocation_Load(object sender, EventArgs e)
        {
            context=new LibManagementEntities();
            lsbMaster.SetDataSource(context.Locations.ToList(), "LocationName", "LocationId");
        }

        private void lsbMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                OLocation = context.Locations.Single(x => x.LocationId == (decimal)lsbMaster.SelectedValue);
                txtName.Text = OLocation.LocationName;
            }
            catch (Exception)
            {
            }
        }
    }
}
